﻿using System.Collections.Generic;

namespace PC1
{
    public class RamSetter
    {
        private readonly Dictionary<string, List<int>> _addLabelLater = new Dictionary<string, List<int>>();

        private readonly Dictionary<string, int> _labels = new Dictionary<string, int>();

        private readonly IRam _ram;

        private int _rf;

        public RamSetter(IRam ram)
        {
            _ram = ram;
            _rf = 0;
        }

        public RamSetter Add(CommandMc command)
        {
            _ram[_rf] = (int)command;
            _rf++;
            return this;
        }

        public RamSetter Add(int d)
        {
            _ram[_rf] = d;
            _rf++;
            return this;
        }

        public RamSetter Add(string label)
        {
            int rf;
            if (_labels.TryGetValue(label, out rf))
            {
                return Add(rf);
            }

            _addLabelLater[label] = new List<int> { _rf };
            _rf++;

            return this;
        }

        public RamSetter Add(CommandMc command, int d)
        {
            Add(command);
            Add(d);
            return this;
        }

        public RamSetter Add(CommandMc command, string label)
        {
            Add(command);
            Add(label);
            return this;
        }

        public RamSetter Label(string label)
        {
            _labels[label] = _rf;

            List<int> rfs;
            if (_addLabelLater.TryGetValue(label, out rfs))
            {
                _addLabelLater.Remove(label);
                for (var i = 0; i < rfs.Count; i++)
                {
                    _ram[rfs[i]] = _rf;
                }
            }

            return this;
        }
    }
}